package com.app.xinfadi.base;

import android.app.Application;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.Vibrator;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.WindowManager;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.app.xinfadi.R;
import com.app.xinfadi.dao_bean.ceshi.Ceshi;
import com.app.xinfadi.db.DBHelper;
import com.app.xinfadi.util.NetUtil;
import com.app.xinfadi.util.Utility;
import com.app.xinfadi.widget.gson.GsonRequest;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

import java.util.LinkedHashMap;


public class MyApplication extends Application {
    private static final String TAG = "MY_APPLICATION";
    public static int system_status_bar_height = 0;
    /**
     * 表情包
     */
    public static LinkedHashMap<String, Bitmap> emotionsPics = new LinkedHashMap<String, Bitmap>();
    //    private RefWatcher refWatcher;
    private static ImageLoaderConfiguration config;
    /**
     * Global request queue for Volley
     */
    private static RequestQueue mRequestQueue;
    /**
     * A singleton instance of the application class for easy access in other
     * places
     */
    private static MyApplication sInstance;
    public Vibrator mVibrator;
    public int screenWidth;
    public int screenHeight;
    public int statusBarHeight;
    public int actionBarHeight;
    public boolean isOffLine = false;

    /**
     * @return ApplicationController singleton instance
     */
    public static synchronized MyApplication getInstance() {
        return sInstance;
    }

    @SuppressWarnings("deprecation")
    public void onCreate() {
        super.onCreate();
        sInstance = this;
        initWindowsData();
//        initCaseData();
        initImageLoader(getApplicationContext());
//        refWatcher = LeakCanary.install(this);
        initStetho();initDb();
//        Ceshi ceshi = new Ceshi();
//        ceshi.testProdect();

    }

    private void initWindowsData() {
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        screenWidth = wm.getDefaultDisplay().getWidth();// 手机屏幕的宽度
        screenHeight = wm.getDefaultDisplay().getHeight();// 手机屏幕的高度
        statusBarHeight = getStatusBarHeight();
        actionBarHeight = getActionBarHeight();
    }
    private void initDb() {
        DBHelper.getInstance(this);
    }
    private int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    private int getActionBarHeight() {
        return Utility.getThemeAttributeDimensionSize(this, android.R.attr.actionBarSize);
    }


    private void initStetho() {
//        Stetho.initialize(
//                Stetho.newInitializerBuilder(this)
//                        .enableDumpapp(
//                                Stetho.defaultDumperPluginsProvider(this))
//                        .enableWebKitInspector(
//                                Stetho.defaultInspectorModulesProvider(this))
//                        .build());
    }


    public ImageLoaderConfiguration getImageLoaderConfiguration() {
        if (config != null) {
            return config;
        }
        return null;
    }

    public static void initImageLoader(Context context) {
        // This configuration tuning is custom. You can tune every option, you
        // may tune some of them,
        // or you can create default configuration by
        // ImageLoaderConfiguration.createDefault(this);
        // method.
        DisplayImageOptions option = new DisplayImageOptions.Builder().showImageOnFail(R.mipmap.image_failed)
                //.cacheInMemory(true)
                .cacheOnDisk(true).bitmapConfig(Bitmap.Config.ARGB_4444).build();

        config = new ImageLoaderConfiguration.Builder(context)
                .threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory()
                        // 50 Mb
                .diskCacheFileNameGenerator(new Md5FileNameGenerator()).diskCacheSize(50 * 1024 * 1024)
                .memoryCache(new LruMemoryCache(2 * 1024 * 1024)).threadPoolSize(5)
                        // .memoryCacheSize(1 * 1024 * 1024)
                        // 输出log
                        // .writeDebugLogs()
                        // Remove for release app
                .tasksProcessingOrder(QueueProcessingType.LIFO).defaultDisplayImageOptions(option).build();

        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config);
    }

//    public static RefWatcher getRefWatcher(Context context) {
//        MyApplication application = (MyApplication) context.getApplicationContext();
//        return application.refWatcher;
//    }

    /**
     * @return The Volley Request queue, the queue will be created if it is null
     */
    public RequestQueue getRequestQueue() {
        // lazy initialize the request queue, the queue instance will be
        // created when it is accessed for the first time
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }
        return mRequestQueue;
    }

    /**
     * Adds the specified request to the global queue, if tag is specified then
     * it is used else Default TAG is used.
     * 有用网络连接检测
     *
     * @param req
     * @param tag
     */

    public <T> void addToRequestQueue(GsonRequest<T> req, String tag) {
        if (NetUtil.isNetAvailable(getApplicationContext())) {
            // set the default tag if tag is empty
            req.setRetryPolicy(new DefaultRetryPolicy(600 * 1000, 1, 1.0f));
            req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
//        VolleyLog.d("Adding request to queue: %s", req.getUrl());
            getRequestQueue().add(req);
        } else {
//            Toast.makeText(getApplicationContext(), "网络未连接！", Toast.LENGTH_SHORT).show();
            /**
             * 网络未连接 40001
             */
            req.parseErrorListener(40001);
        }
    }

    /**
     * Adds the specified request to the global queue using the Default TAG.
     * 没有网络连接检测
     *
     * @param req
     */
    public <T> void addToRequestQueue(Request<T> req) {
        // set the default tag if tag is empty
        req.setTag(TAG);
        req.setRetryPolicy(new DefaultRetryPolicy(600* 1000, 1, 1.0f));
        getRequestQueue().add(req);
    }

    /**
     * Cancels all pending requests by the specified TAG, it is important to
     * specify a TAG so that the pending/ongoing requests can be cancelled.
     *
     * @param tag
     */
    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
    }

    public void onDestory() {
    }

    /**
     * 获取手机串号
     *
     * @return
     */
    public String getDeviceId() {
        TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        String imei = tm.getDeviceId();
        return imei;
    }

    /**
     * 应用名称
     *
     * @return
     */
    public String getApplicationName() {
        PackageManager packageManager = null;
        ApplicationInfo applicationInfo = null;
        try {
            packageManager = MyApplication.getInstance().getApplicationContext().getPackageManager();
            applicationInfo = packageManager.getApplicationInfo(MyApplication.getInstance().getApplicationContext().getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            applicationInfo = null;
        }
        String applicationName =
                (String) packageManager.getApplicationLabel(applicationInfo);
        return applicationName;
    }

    /**
     * 退出程序
     */
    public void exist() {
        android.os.Process.killProcess(android.os.Process.myPid());
    }


}
